import { Component, OnInit, Output, EventEmitter } from "@angular/core";
import { IntervalObservable } from "rxjs/observable/IntervalObservable";
import { Subscription } from "rxjs/Subscription";

import { UserService } from "./../user.service";
import { User } from "./../user.model";

@Component({
  selector: "user-setting",
  templateUrl: "setting.component.html",
  styleUrls: ["setting.component.less"]
})
export class UserSettingComponent implements OnInit {
  @Output() setModal = new EventEmitter();
  errText: string = "";
  waitTime: number = 60;
  countdown: Subscription;
  user: User;
  constructor(private userService: UserService) { }

  ngOnInit() {
    this.stopCountdown();
  }

  private checkInfoValid() {
    // 校验手机号是否可用
    if (!this.user || !(this.user).hasOwnProperty("username")) {
      this.errText = "手机号码不能为空";
      return false;
    } else {
      let fmt = /^\d{11}$/;
      // let fmt = /^1[3578]\d{9}$/;
      if (!fmt.test(this.user.username)) {
        this.errText = "手机号格式不正确";
        return false;
      }
    }
    return true;
  }

  private stopCountdown() {
    if (this.countdown) {
      this.countdown = undefined;
    }
  }

  sendOTP() {
    this.userService.sendOTPs(this.user.username).subscribe((data) => {
      this.countdown = IntervalObservable.create(1000).subscribe(() => {
        this.waitTime -= 1;
        if (this.waitTime <= 0) {
          this.stopCountdown();
        }
      });
    }, (resp) => {
      console.log("sms/otps failed data:", resp);
      // toolTip.alertTip(resp.data);
      // toolTip.alertTip("手机号码不正确");
      this.errText = "手机号码不正确";
    });
  }

  changeModal(action: string) {
    this.errText = "";
    this.setModal.emit(action);
  }
}